import 'package:flutter/material.dart';

typedef LoadMoreCallback = Future<void> Function();

/// 封装下拉刷新与加载更多
class LoadMoreChild extends StatefulWidget {
  const LoadMoreChild({
    super.key,
    required this.child,
    this.loadMore,
    this.hasMore = false,
  });

  final LoadMoreCallback? loadMore;
  final bool hasMore;
  final Widget child;

  @override
  State<LoadMoreChild> createState() => _LoadMoreChildState();
}

class _LoadMoreChildState extends State<LoadMoreChild> {
  final isLoading = ValueNotifier(false);
  final rebuild = ValueNotifier(false);

  Future<void> loadMoreFunc() async {
    if (widget.loadMore == null) {
      return;
    }
    if (isLoading.value) {
      return;
    }
    if (!widget.hasMore) {
      return;
    }
    isLoading.value = true;
    await widget.loadMore?.call();
    isLoading.value = false;
    rebuild.value = !rebuild.value;
  }

  @override
  Widget build(BuildContext context) {
    return NotificationListener<ScrollNotification>(
      onNotification: (ScrollNotification note) {
        /// 确保是垂直方向滚动，且滑动至底部
        final metrics = note.metrics;
        if (metrics.pixels == metrics.maxScrollExtent &&
            metrics.axis == Axis.vertical &&
            metrics.atEdge) {
          loadMoreFunc();
        }
        return false;
      },
      child: Builder(
        builder: (context) {
          final list = [
            ValueListenableBuilder(
                valueListenable: rebuild,
                builder: (context, v, c) {
                  return widget.child;
                }),
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: ValueListenableBuilder(
                  valueListenable: isLoading,
                  builder: (context, v, c) {
                    return AnimatedCrossFade(
                      duration: const Duration(milliseconds: 300),
                      firstChild: const SizedBox.shrink(),
                      secondChild: const FooterListWidget(),
                      crossFadeState: v
                          ? CrossFadeState.showSecond
                          : CrossFadeState.showFirst,
                    );
                  }),
            ),
          ];
          return Stack(
            children: list,
          );
        },
      ),
    );
  }
}

class FooterListWidget extends StatelessWidget {
  const FooterListWidget({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 10),
        alignment: Alignment.center,
        child: const Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(width: 20, height: 20, child: CircularProgressIndicator()),
            SizedBox(width: 10),
            Text('loading')
          ],
        ),
      ),
    );
  }
}
